<?php
declare (strict_types=1);

namespace app\scan_bag\controller;

use app\admin\model\base\User;
use app\admin\model\iot\Device;
use app\admin\model\iot\ScanBagDay;
use app\admin\model\iot\ScanBagStrategy as ScanBagStrategyModel;
use app\admin\model\iot\ScanBagWay;
use app\admin\service\base\JwtService;
use app\BaseController;
use app\BaseService;
use app\scan_bag\service\ScanBagV1Service;
use app\scan_bag\service\ScanBagV2Service;
use redis\RedisTools2;
use think\App;
use think\facade\Cache;
use think\facade\Cookie;
use think\response\Json;
use wechat\WsOfficialAccount;

/**
 * 取袋策略
 */
class ScanBagStrategy extends BaseController
{

    /**
     * 根据设备返回对应的取袋模块
     * @param ScanBagV1Service $scanBagV1Service
     * @return Json
     */
    public function getMacIdWay(ScanBagV1Service $scanBagV1Service):Json
    {
        $mac_id = $this->request->param('mac_id/s');
        //获取设备类型
        //判断是v1设备还是v2系统设备
        $where = ['mac_id' => $mac_id];
        $device = Device::where($where)->cache(true, 60)->value('id');
        $num =1;
        $user_id = WS_USER_ID;
        if($device){
            $day = ScanBagDay::getUserIdDayNum($user_id);
            $num = $day['day_used'];
            $num ++;
        }else{
            $data = $scanBagV1Service->userScanNum($user_id, $mac_id);
            $data=(json_decode($data->getContent(),true));
            if(isset($data['data'][0]['global_task_num'])){
                $num = $data['data'][0]['global_task_num'];
                $num =$num>3?3:$num;
            }else{
                $num = 3;
            }

        }
        $num =$num>3?3:$num;
        $arr = [1=>'first',2=>'second',3=>'third'];
        //获取取袋路径
        $WayInfo = ScanBagStrategyModel::getMacIdWay($mac_id,$arr[$num]);
        $WayInfo['num'] =$num;
        //把路径信息和出袋次数存缓存
        Cookie::forever('cookie_strategy_user', $user_id);
        $tKey = BaseService::generateScanBagStrategyKey($user_id);
        Cache::set($tKey, json_encode($WayInfo), 6000);
        return jsonReturn(1, $WayInfo);
    }

    /**
     * 微信H5用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wechatLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->wechatH5Login2($code);
        if ($bool['bool']) {
            //签发token
            $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
            if ($jst_data['bool']) {
                return jsonReturn(1, $bool, '登录成功');
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }





}
